<template>
  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">基础信息</div>
      </div>
      <div class="content_main">
        <el-form 
          ref="formRef" 
          :inline="true" 
          :model="formData.data" 
          :rules="formRules" 
          class="-mb-15px"
          label-width="auto"
        >
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="合同名称" prop="name">
                <el-input class="formInp" v-model="formData.data.name" clearable placeholder="请输入合同名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同编号" prop="number">
                <el-input class="formInp" v-model="formData.data.number" clearable placeholder="请输入合同编号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额（含税）" prop="amountWithTax">
                <el-input-number 
                  class="formInp" 
                  v-model="formData.data.amountWithTax" 
                  controls-position="right" 
                  :min="0"
                  placeholder="请输入合同含税金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额（不含税）" prop="amountWithoutTax">
                <el-input-number 
                  class="formInp" 
                  v-model="formData.data.amountWithoutTax" 
                  controls-position="right" 
                  :min="0"
                  placeholder="请输入合同不含税金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同类别" prop="category">
                <el-select class="formInp" v-model="formData.data.category" placeholder="请选择合同类别">
                  <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同类型" prop="type">
                <el-select class="formInp" v-model="formData.data.type" placeholder="请选择合同类型">
                  <el-option v-for="item in contractTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="department">
                <el-tree-select
                  class="formInp"
                  v-model="formData.data.department"
                  :data="deptTree"
                  filterable
                  clearable
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  placeholder="请选择所属部门"
                  value-key="deptId"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同时间" prop="contractTime">
                <el-date-picker
                  v-model="formData.data.contractTime"
                  class="!w-360px"
                  type="datetimerange"
                  placeholder="请选择合同时间"
                  range-separator="~" 
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  @change="e => formData.data.contractTime = [formatDateToYMDHMS(e[0]), formatDateToYMDHMS(e[1])]"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">预采材料</div>
      </div>
      <div class="content_main">
        <div class="flex-s mb-12">
          <el-upload
            :http-request="ImprotRequest"
            :show-file-list="false"
            :before-upload="beforeFileUpload"
          >
            <el-button>导入材料</el-button>
          </el-upload>
          <span class="improtTxt ml-12" href="#" @click="downloadTemplate">下载导入模板</span>
        </div>
        <el-table :data="formData.data.materials">
          <el-table-column align="center" label="材料名称" prop="name">
            <template #default="scope">
              <el-input v-if="scope.row.editable" v-model="scope.row.name" placeholder="请输入材料名称" />
              <div v-else>{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="规格型号" prop="specification">
            <template #default="scope">
              <el-input v-if="scope.row.editable" v-model="scope.row.specification" placeholder="请输入规格型号" />
              <div v-else>{{ scope.row.specification }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="单位" prop="unit">
            <template #default="scope">
              <el-input v-if="scope.row.editable" v-model="scope.row.unit" placeholder="请输入单位" />
              <div v-else>{{ scope.row.unit }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="采购数量" prop="quantity">
            <template #default="scope">
              <el-input-number 
                class="formInp"
                v-if="scope.row.editable" 
                controls-position="right" 
                :min="1" 
                v-model="scope.row.quantity" 
                placeholder="请输入采购数量" 
              />
              <div v-else>{{ scope.row.quantity }}</div>
            </template>
          </el-table-column>
          <el-table-column :width="200" align="center" label="操作">
            <template #default="scope">
  
              <div v-if="scope.row.editable">
                <el-button link type="info" @click="cancle(scope.$index)">取消</el-button>
                <el-button link type="primary" @click="save(scope.row, scope.$index)">保存</el-button>
              </div>
              <div v-else>
                <el-button link type="primary" @click="edit(scope.$index)">
                  编辑
                </el-button>
                <el-popconfirm
                  class="box-item"
                  title="确定删除？"
                  placement="top-end"
                  @confirm="del(scope.$index)"
                >
                  <template #reference>
                    <el-button link type="danger">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
  
        </el-table>
        <el-button class="addRow" @click="addRow" plain>
          <el-icon class="mr-6"><Plus /></el-icon>  添加
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">合作单位</div>
      </div>
      <div class="content_main">
        <el-table :data="formData.data.companyAll">
          <template v-for="item in companiesColumn" :key="item.prop">
            <el-table-column
              :width="item.width"
              :align="item.align ? item.align : 'center'" 
              :label="item.label"
              :prop="item.prop"
            />
          </template>
    
          <el-table-column :width="100" align="center" label="操作">
            <template #default="scope">
              <el-button link type="danger" @click="companiesDel(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
    
        </el-table>
        <el-button class="addRow" @click="addCompanies" plain>
          <el-icon class="mr-6"><Plus /></el-icon>  添加
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">关联合同</div>
      </div>
      <div class="content_main">
        <el-table :data="formData.data.relationAll">
          <template v-for="item in relationsColumn" :key="item.prop">
            <el-table-column
              :width="item.width"
              :align="item.align ? item.align : 'center'" 
              :label="item.label"
              :prop="item.prop"
            >
              <template #default="scope">
                <div v-if="item.prop === 'number'" @click="goContract(scope.row.id)">
                  <span style="color: #409eff;cursor: pointer;">{{ scope.row.number }}</span>
                </div>
                <div v-else-if="item.prop == 'category'">
                  <span v-if="scope.row.category || scope.row.category === 0">{{ categoryList.find(item => item.id === scope.row.category).name }}</span>
                  <span v-else>-</span>
                </div>
                <div v-else-if="item.prop == 'type'">
                  <span v-if="scope.row.type || scope.row.type === 0">{{ contractTypeList.find(item => item.value === scope.row.type).label }}</span>
                  <span v-else>-</span>
                </div>
                <div v-else-if="item.prop === 'department'">{{ scope.row.department ? findDeptNameById(deptTree, scope.row.department) : '-' }}</div>
                <div v-else>
                  {{ scope.row[item.prop] || (item.type === 'number' ? '0.00' : '-') }}
                </div>
              </template>
            </el-table-column>
          </template>
    
          <el-table-column :width="100" align="center" label="操作">
            <template #default="scope">
              <el-button link type="danger" @click="relationsDel(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
    
        </el-table>
        <el-button class="addRow" @click="addRelations" plain>
          <el-icon class="mr-6"><Plus /></el-icon>  添加
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title flex-s">
          <span class="mr-6">动态成本</span>
          <el-tooltip
            class="box-item"
            effect="light"
            placement="top-start"
          >
            <template #content>
              动态成本合计金额计算公式：<br/>
              1.动态成本含税合计金额&nbsp;=&nbsp;合同金额（含税）+ &nbsp;成本含税金额合计；<br/>
              2.动态成本不含税合计金额&nbsp;=&nbsp;合同金额（不含税）+ &nbsp;成本不含税金额合计；
            </template>
            <el-icon><Warning /></el-icon>
          </el-tooltip>
        </div>
      </div>
      <div class="content_main">
        <el-table :data="formData.data.costs" :row-class-name="tableRowClassName">
          <el-table-column align="center" label="成本名称" prop="name" width="230">
            <template #default="scope">
              <el-input v-if="scope.row.editable" v-model="scope.row.name" placeholder="请输入成本名称" />
              <div v-else>{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="成本含税金额" prop="amountWithTax" width="230">
            <template #default="scope">
              <el-input-number 
                class="formInp"
                controls-position="right" 
                v-if="scope.row.editable" 
                :min="0" 
                v-model="scope.row.amountWithTax" 
                placeholder="请输入成本含税金额"
                @input="e => amountWithTaxChange(e, scope.$index)"
              />
              <div v-else>{{ scope.row.amountWithTax }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="税率" prop="taxRate" width="230">
            <template #default="scope">
              <el-input-number 
                class="formInp"
                controls-position="right" 
                v-if="scope.row.editable" 
                :min="0" 
                v-model="scope.row.taxRate" 
                placeholder="请输入税率"
                @input="e => taxRateChange(e, scope.$index)"
              />
              <div v-else>
                <span v-if="scope.row.name === '合计'"></span>
                <span v-else>{{ scope.row.taxRate }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="成本不含税金额" prop="amountWithoutTax" width="230">
            <template #default="scope">
              <el-input-number class="formInp" controls-position="right" v-if="scope.row.editable" disabled v-model="scope.row.amountWithoutTax" placeholder="请输入成本不含税金额" />
              <div v-else>{{ scope.row.amountWithoutTax }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="附件" prop="attachment" width="270">
            <template #default="scope">
              <div v-if="scope.row.name === '合计'"></div>
              <div v-else>
                <div v-if="scope.row.editable">
                  <div class="flex-s" v-if="scope.row.attachment">
                    <span class="!w-160px ellipsis">{{ scope.row.attachment.slice(scope.row.attachment.lastIndexOf('/') + 1) }}</span>
                    
                    <span class="mx-12">
                      <el-upload
                          :http-request="e => requestTable(e, scope.$index)"
                          :show-file-list="false"
                          :before-upload="beforeUpload"
                        >
                          <template #trigger><a href="#">修改</a></template>
                        </el-upload>
                    </span>
                    <a :href="scope.row.attachment">下载</a>
                  </div>
                  
                  <el-upload
                    v-else
                    :http-request="e => requestTable(e, scope.$index)"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                  >
                    <template #trigger><span style="color: #409eff;">上传附件</span></template>
                  </el-upload>

                </div>
                <div class="flex-s" v-else>
                  <div class="!w-180px ellipsis">{{ scope.row.attachment.slice(scope.row.attachment.lastIndexOf('/') + 1) }}</div>
                  <a class="ml-12" :href="scope.row.attachment">下载</a>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" width="230">
            <template #default="scope">
              <span v-if="scope.row.name === '合计'"></span>
              <span v-else>{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-'  }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建人" prop="creator">
            <template #default="scope">
              <span v-if="scope.row.name === '合计'"></span>
              <span v-else>
                {{ userList.find(item => item.id == scope.row.creator)?.username || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :width="200" align="center" label="操作" fixed="right">
            <template #default="scope">
              <div v-if="scope.row.name === '合计'"></div>
              <div v-else>
                <div v-if="scope.row.editable">
                  <el-button link type="info" @click="cancleCosts(scope.$index)">取消</el-button>
                  <el-button link type="primary" @click="saveCosts(scope.row, scope.$index)">保存</el-button>
                </div>
                <div v-else>
                  <el-button link type="primary" @click="editCosts(scope.$index)">
                    编辑
                  </el-button>
                  <el-popconfirm
                    class="box-item"
                    title="确定删除？"
                    placement="top-end"
                    @confirm="delCosts(scope.$index)"
                  >
                    <template #reference>
                      <el-button link type="danger">
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </template>
          </el-table-column>
  
        </el-table>
        <el-button class="addRow" @click="addCostsRow" plain>
          <el-icon class="mr-6"><Plus /></el-icon>  添加
        </el-button>
      </div>
    </div>
    <div class="content mb-0">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">附加信息</div>
      </div>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input
              v-model="formData.data.remark"
              type="textarea"
              :autosize="{ minRows: 8}"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传附件">
            <div class="upload_box" style="width: 100%;">
              <UploadFile
                v-model="formData.data.attachment"
                class="upload-demo"
                :http-request="customRequest"
                :fileSize="20"
                :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                :limit="10"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
  <ContentWrap class="flex-c">
    <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm">确定</el-button>
    <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
  </ContentWrap>

  <!-- 合作单位弹窗 - 勾选数据 -->
  <companiesDialog ref="companiesDialogRef" @change="companiesChange"/>

  <!-- 关联合同弹窗 - 勾选数据 -->
  <relationsDialog ref="relationsDialogRef" @change="relationsChange"/>
</template>
<script setup>
  import {ref, reactive, inject} from "vue"
  import XLSTYLE from "xlsx-js-style";
  import * as ContractApi from '@/api/viewsApi/contract'
  import { Plus, Warning } from '@element-plus/icons-vue'
  import { defaultProps, handleTree } from '@/utils/tree'
  import { formRules, companiesColumn, relationsColumn } from './formRules'
  import { formatDateToYMDHMS, parseYMDToDate } from '@/utils/index'
  import { dataConversionUtil } from "@/utils/excel";
  import { ElMessage, ElMessageBox } from 'element-plus'
  import companiesDialog from './companiesDialog.vue'
  import relationsDialog from './relationsDialog.vue'
  import { updateFile } from "@/api/infra/file/index.ts"
  import { formatDate } from '@/utils/formatTime' // 时间戳转日期
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  const { wsCache } = useCache('sessionStorage')
  const userList = wsCache.get(CACHE_KEY.USER_LIST) || []
  
  import { UploadFile } from "@/components/UploadFile/index.ts"
  let setPageStatus = inject('setPageStatus', () => {});
  const deptTree = inject('deptTree')
  const contractTypeList = inject('contractTypeList')
  const categoryList = inject('categoryList')
  const message = useMessage() // 消息弹窗
  const router = useRouter()
  const formRef = ref(null)
  const goBack = inject('goBack', () => {})
  const companiesDialogRef = ref(null)
  const relationsDialogRef = ref(null)
  const formData = reactive({
    data: {
      name: '', // 合同名称
      number: '', // 合同编号
      category: '', // 合同类别
      type: '', // 合同类型
      department: '', // 所属部门
      amountWithTax: '', // 合同金额（含税）
      amountWithoutTax: '', // 合同金额（不含税）
      contractTime: '', // 合同时间
      createTime: '',
      updateTime: '',
      materials: [], // 预采材料
      companyAll: [], // 合作单位
      relationAll: [], // 关联合同
      costs: [] // 动态成本
    }
  })
  let loading = ref(false)
  let pageStatus = ref(1) // 1新增  2编辑
  let copyData = ref([])

  /** 初始化 **/
  const init = (type, id) => {
    console.log(userList, 'userList...');
    
    pageStatus.value = type
    if (id) {
      getDetails(id)
    }else{
      formData.data = {
        name: '', // 合同名称
        number: '', // 合同编号
        category: '', // 合同类别
        type: '', // 合同类型
        department: '', // 所属部门
        amountWithTax: '', // 合同金额（含税）
        amountWithoutTax: '', // 合同金额（不含税）
        contractTime: '', // 合同时间
        materials: [], // 预采材料
        companyAll: [], // 合作单位
        relationAll: [], // 关联合同
        costs: [] // 动态成本
      }
      modalAmount()
    }
  }
  /** 查询详情信息 */
  const getDetails = async (id) => {
    loading.value = true
    try {
      const data = await ContractApi.getContractDetail(id)
      if(data.costs.length > 0){
        data.costs.forEach(item => {
          item.amountWithTax = (item.amountWithTax / 100).toFixed(2)
          item.amountWithoutTax = (item.amountWithoutTax / 100).toFixed(2)
        })
      }

      data.amountWithTax = (data.amountWithTax / 100).toFixed(2)
      data.amountWithoutTax = (data.amountWithoutTax / 100).toFixed(2)
      formData.data = data
      modalAmount()
    } finally {
      loading.value = false
    }
  }
  
  /** 预采材料 - 导入数据逻辑处理 - 开始 */
  const downloadTemplate = () => {
    console.log(XLSTYLE, '下载导入模板');
    const tableHeader = [[ "材料名称", "规格型号", "单位","预采数量"]];
    const dataList = [
      ["伊利纯牛奶", "350ml", "件", "50"],
      ["菊乐酸奶", "350ml", "件", "50"],
      ["蒙牛纯牛奶", "350ml", "件", "50"],
    ];
    dataConversionUtil.dataToExcel("预采材料导入模板", tableHeader, dataList);
    message.success("下载模板成功!");
  }
  const ImprotRequest = async (options) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await ContractApi.ImprotContractl(upFilesData)
      let newData = formData.data.materials.concat(res.data)
      formData.data.materials = newData
    }finally {
      
    }
    
  }
  const beforeFileUpload = (rawFile) => {
    let fileExtension = ''
    if (rawFile.name.lastIndexOf('.') > -1) {
      fileExtension = rawFile.name.slice(rawFile.name.lastIndexOf('.') + 1)
    }
    let excelType = ['xlsx', 'xls']
    const isImg = excelType.some((type) => {
      if (rawFile.type.indexOf(type) > -1) return true
      return !!(fileExtension && fileExtension.indexOf(type) > -1)
    })

    if (!isImg) {
      message.error(`文件格式不正确, 请上传excel的${excelType.join('/')}格式!`)
      return false
    } else if (rawFile.size / 1024 / 1024 > 20) {
      message.error('文件大小不能超过 20MB!')
      return false
    }
    return true
  }
  /** 预采材料 - 导入数据逻辑处理 - 结束 */

  
  /** 预采材料 - 表格逻辑处理 - 开始 */
  const addRow = () => {
    let bankList = JSON.parse(JSON.stringify(formData.data.materials))
    copyData.value = JSON.parse(JSON.stringify(bankList))
    let flag = bankList.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    bankList.push({
      name: '',
      specification: '',
      unit: '',
      quantity: '',
      editable: true,
    })
    formData.data.materials = bankList
  }

  const edit = (index) => {
    let materials = JSON.parse(JSON.stringify(formData.data.materials))
    let flag = materials.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    copyData.value = JSON.parse(JSON.stringify(materials))
    console.log(copyData.value);
    materials[index].editable = true
    formData.data.materials = materials
  }

  const del = (index) => {
    let materials = JSON.parse(JSON.stringify(formData.data.materials))
    materials.splice(index, 1)
    formData.data.materials = materials
  }

  const cancle = () => {
    let materials = JSON.parse(JSON.stringify(copyData.value))
    formData.data.materials = materials
  }

  const save = (row, index) => {
    let materials = JSON.parse(JSON.stringify(formData.data.materials))

    const {name, specification, unit, quantity} = row
    if (!name) {
      message.warning('请输入材料名称')
      return
    }
    if (!specification) {
      message.warning('请输入规格型号')
      return
    }
    if (!unit) {
      message.warning('请输入单位名称')
      return
    }
    if (!quantity) {
      message.warning('请输入采购数量')
      return
    }
    materials.forEach(item => item.editable = false)
    formData.data.materials = materials
  }
  /** 预采材料 - 表格逻辑处理 - 结束 */


  /** 合作单位逻辑处理 - 开始 */
  const addCompanies = () => {
    companiesDialogRef.value.init()
  }
  const companiesChange = (data) => {
    if(formData.data.companyAll.length > 0) {
      let newData = formData.data.companyAll.concat(data)
      // 使用 reduce 去重
      newData = newData.reduce((acc, cur) => {
        if (!acc.some(item => item.id === cur.id)) {
          acc.push(cur)
        }
        return acc
      }, [])
      formData.data.companyAll = newData
    }else{
      formData.data.companyAll = data
    }
  }
  const companiesDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.companyAll.splice(index, 1)
    } catch {}

  }
  /** 合作单位逻辑处理 - 结束 */


  /** 关联合同逻辑处理 - 开始 */
  const addRelations = () => {
    relationsDialogRef.value.init()
  }
  const relationsChange = (data) => {
    if(formData.data.relationAll.length > 0) {
      let newData = formData.data.relationAll.concat(data)
      // 使用 reduce 去重
      newData = newData.reduce((acc, cur) => {
        if (!acc.some(item => item.id === cur.id)) {
          acc.push(cur)
        }
        return acc
      }, [])
      formData.data.relationAll = newData
    }else{
      formData.data.relationAll = data
    }
  }
  const relationsDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.relationAll.splice(index, 1)
    } catch {}
  }
  const goContract = (id) => {
    router.push({
      path: '/contract',
      query: {
        id,
      }
    })
  }
  /** 关联合同逻辑处理 - 结束 */


  /** 动态成本 - 逻辑处理 - 开始 */
  const tableRowClassName = ({ row, rowIndex }) => {
    if (row.name === '合计') {
      return "bg-black"
    }
  }

  const amountWithTaxChange = (e, index) => {
    let taxRate = formData.data.costs[index].taxRate
    let amountWithoutTax = (e - (e * taxRate / 100)).toFixed(2)
    formData.data.costs[index].amountWithoutTax = amountWithoutTax
  }
  const taxRateChange = (e, index) => {
    let amountWithTax = formData.data.costs[index].amountWithTax
    let amountWithoutTax = (amountWithTax - (amountWithTax * e / 100)).toFixed(2)
    formData.data.costs[index].amountWithoutTax = amountWithoutTax
  }

  const addCostsRow = () => {
    let bankList = JSON.parse(JSON.stringify(formData.data.costs))
    copyData.value = JSON.parse(JSON.stringify(bankList))
    let flag = bankList.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    let costsItem = {
      name: '',
      amountWithTax: null,
      amountWithoutTax: null,
      taxRate: null,
      attachment: '',
      createTime: '',
      creator: '',
      editable: true,
    }
    bankList.splice(bankList.length - 1, 0, costsItem);
    formData.data.costs = bankList
  }

  const editCosts = (index) => {
    let costs = JSON.parse(JSON.stringify(formData.data.costs))
    let flag = costs.find(item => item.editable)
    if (flag) {
      message.warning('请先保存当前数据')
      return
    }
    copyData.value = JSON.parse(JSON.stringify(costs))
    console.log(copyData.value);
    costs[index].editable = true
    formData.data.costs = costs
  }

  const delCosts = (index) => {
    let costs = JSON.parse(JSON.stringify(formData.data.costs))
    costs.splice(index, 1)
    formData.data.costs = costs
    modalAmount()
  }

  const cancleCosts = () => {
    let costs = JSON.parse(JSON.stringify(copyData.value))
    formData.data.costs = costs
  }

  const saveCosts = (row, index) => {
    let costs = JSON.parse(JSON.stringify(formData.data.costs))

    const {name, amountWithTax, amountWithoutTax, taxRate, attachment} = row
    if (!name) {
      message.warning('请输入成本名称')
      return
    }
    if (!amountWithTax && amountWithTax !== 0) {
      message.warning('请输入成本含税金额')
      return
    }
    if (!amountWithoutTax && amountWithoutTax !== 0) {
      message.warning('请输入成本不含税金额')
      return
    }
    if (!taxRate && taxRate !== 0) {
      message.warning('请输入税率')
      return
    }
    if (!attachment) {
      message.warning('请上传成本附件')
      return
    }
    costs.forEach(item => item.editable = false)
    formData.data.costs = costs
    modalAmount()
  }

  const requestTable = async (options, index) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      formData.data.costs[index].attachment = res.data
    }finally {
      
    }
  }

  // 文件上传之前判断
  const beforeUpload = (file) => {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
    }
    
    const fileType = ['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
    const isImg = fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true
      return !!(fileExtension && fileExtension.indexOf(type) > -1)
    })
    const isLimit = file.size < 20 * 1024 * 1024
    if (!isImg) {
      ElMessage.error(`文件格式不正确, 请上传${fileType.join('/')}格式!`)
      return false
    }
    if (!isLimit) {
      ElMessage.error(`上传文件大小不能超过${20}MB!`)
      return false
    }
  }

  // 计算表格金额
  function modalAmount() {
    const {amountWithTax, amountWithoutTax} = formData.data
    var filterData = formData.data.costs.filter(item => item.name !== '合计')

    let amountWithTaxSum = Number(amountWithTax)
    let amountWithoutTaxSum = Number(amountWithoutTax)
    for(let item of filterData){
        amountWithTaxSum += Number(item.amountWithTax)
        amountWithoutTaxSum += Number(item.amountWithoutTax)
    }

    amountWithTaxSum = amountWithTaxSum.toFixed(2)
    amountWithoutTaxSum = amountWithoutTaxSum.toFixed(2)

    filterData.push({
        id: 0,
        name: '合计',
        amountWithTax: amountWithTaxSum > 0 ? amountWithTaxSum : '0.00',
        taxRate: null,
        amountWithoutTax: amountWithoutTaxSum > 0 ? amountWithoutTaxSum : '0.00',
        attachment: null,
        createTime: null,
        creator: null,
        editable: false,
    })

    formData.data.costs = filterData
  }
  /** 动态成本 - 逻辑处理 - 结束 */



  const customRequest = async (options) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      formData.data.attachment.push(res.data)
    }finally {
      
    }
    
  }





  const submitForm = async () => {
    const formEl = formRef.value
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {

      let parmsData = JSON.parse(JSON.stringify(formData.data))
      parmsData.companies = parmsData.companyAll.map(item => {
        return {
          companyId: item.id,
        }
      })
      delete parmsData.companyAll

      let flag = parmsData.materials.find(item => item.editable)
      if(flag){
        message.error('请先保存“预采材料”数据')
        return
      }
      parmsData.materials = parmsData.materials.map(item => {
        return {
          name: item.name,
          quantity: item.quantity,
          specification: item.specification,
          unit: item.unit,
        }
      })

      let flag1 = parmsData.costs.find(item => item.editable)
      if(flag1){
        message.error('请先保存“动态成本”数据')
        return
      }
      parmsData.costs = parmsData.costs.map(item => {
        return {
          amountWithTax: item.amountWithTax,
          amountWithoutTax: item.amountWithoutTax,
          attachment: item.attachment,
          contractId: item.contractId ? item.contractId : '',
          name: item.name,
          taxRate: item.taxRate,
        }
      })


      parmsData.relations = parmsData.relationAll.map(item => {
        return {
          relatedContractId: item.id,
        }
      })
      delete parmsData.relationAll

      parmsData.costs = parmsData.costs.filter(item => item.name !== '合计')
      if(parmsData.costs.length > 0){
        parmsData.costs.forEach(item => {
          item.amountWithTax = item.amountWithTax * 100
          item.amountWithoutTax = item.amountWithoutTax * 100
        })
      }

      if(typeof parmsData.contractTime !== 'number'){
        parmsData.contractTime = toTimestamp(parmsData.contractTime)
      }

      parmsData.amountWithTax = parmsData.amountWithTax * 100
      parmsData.amountWithoutTax = parmsData.amountWithoutTax * 100

      if (pageStatus.value === 1) {
        ContractApi.addContractl(parmsData).then(res => {
          goBack()
          ElMessage.success('新增成功')
        })
      } else {
        ContractApi.editContractl(parmsData).then(res => {
          goBack()
          ElMessage.success('编辑成功')
        })
      }
      }else{
        for(let key in fields){
          ElMessage.error(fields[key][0].message)
        }
      }
    })
  }

  const closeForm = () => {
    // 关闭表单弹窗逻辑
    goBack()
  }
  function findDeptNameById(tree, id) {
    for (const node of tree) {
      if (node.id === id) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const name = findDeptNameById(node.children, id)
        if (name) return name
      }
    }
    return ''
  }
  defineExpose({
    init,
  })

  // 转时间戳
  function toTimestamp(dateStr) {
    console.log(dateStr, '没有传入？？？？');
    
    return new Date(dateStr.replace(/-/g, '/')).getTime();
  }
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    margin-bottom: 24px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
    .content_main {
        width: 100%;
        padding: 0 32px;
        box-sizing: border-box;
    }
}
::v-deep .el-form-item{
  width: 100%;
}
.formInp{
  width: 100%;
}

.addRow{
  margin-top: 12px;
  width: 100%;
}
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  .improtTxt{
    color: #0c84fd;
    cursor: pointer;
    font-size: 12px;
  }

  ::v-deep .bg-black {
      background-color: #F2F2F2;
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      color: #1D1D1D;
  }

.upload_box{
  flex-direction: column;
  .uploader__text{
    margin-top: 6px;
  }
}
::v-deep .el-upload-list{
  overflow-y: scroll;
  height: 120px;
}
</style>
